package com.kuang.exam.modules.sys.lesson.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.kuang.exam.core.api.ApiRest;
import com.kuang.exam.core.api.controller.BaseController;
import com.kuang.exam.core.api.dto.BaseIdsReqDTO;
import com.kuang.exam.core.api.dto.PagingReqDTO;
import com.kuang.exam.core.exception.ServiceException;
import com.kuang.exam.core.utils.excel.ExportExcel;
import com.kuang.exam.core.utils.excel.ImportExcel;
import com.kuang.exam.modules.sys.lesson.dto.SysLessonDTO;
import com.kuang.exam.modules.sys.lesson.dto.UserLessonDTO;
import com.kuang.exam.modules.sys.lesson.dto.export.LessonExportDTO;
import com.kuang.exam.modules.sys.lesson.dto.export.StudentsExportDTO;
import com.kuang.exam.modules.sys.lesson.dto.request.UserLessonSaveDTO;
import com.kuang.exam.modules.sys.lesson.dto.response.LessonStudentsDTO;
import com.kuang.exam.modules.sys.lesson.entity.SysUserLesson;
import com.kuang.exam.modules.sys.lesson.service.SysUserLessonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 管理用户课程控制器
 * </p>
 */
@Api(tags = {"管理用户课程"})
@RestController
@RequestMapping("/exam/api/sys/userLesson")
public class SysUserLessonController extends BaseController {

    @Autowired
    private SysUserLessonService baseService;

    /**
     * 保存或修改用户课程
     *
     * @return
     */
    @ApiOperation(value = "保存或修改")
    @RequestMapping(value = "/save", method = {RequestMethod.POST})
    public ApiRest save(@RequestBody UserLessonSaveDTO reqDTO) {
        if (StringUtils.isBlank(reqDTO.getTeacherId())){
            throw new ServiceException(-1, "未选择老师");
        }
        if (reqDTO.getStudentIds() == null || reqDTO.getStudentIds().size() == 0){
            throw new ServiceException(-1, "未选择学生");
        }
        SysUserLesson sysUserLesson = new SysUserLesson();
        sysUserLesson.setTeacherId(reqDTO.getTeacherId());
        sysUserLesson.setLessonId(reqDTO.getLessonId());
        reqDTO.getStudentIds().forEach(studentId -> {
            sysUserLesson.setId(IdWorker.getIdStr());
            sysUserLesson.setUserId(studentId);
            baseService.save(sysUserLesson);
        });
        return success();
    }

    /**
     * 分页查找
     *
     * @param reqDTO
     * @return
     */
    @ApiOperation(value = "分页查找")
    @RequestMapping(value = "/paging", method = {RequestMethod.POST})
    public ApiRest<IPage<LessonStudentsDTO>> paging(@RequestBody PagingReqDTO<UserLessonDTO> reqDTO) {

        //分页查询并转换
        IPage<LessonStudentsDTO> page = baseService.pagingStudents(reqDTO);
        return super.success(page);
    }


    /**
     * 批量删除
     *
     * @param reqDTO
     * @return
     */
    @ApiOperation(value = "批量删除")
    @RequestMapping(value = "/delete", method = {RequestMethod.POST})
    public ApiRest delete(@RequestBody BaseIdsReqDTO reqDTO) {

        //根据ID删除
        baseService.removeByIds(reqDTO.getIds());
        return super.success();
    }

    /**
     * 下载导入选课名单数据模板
     */
    @ResponseBody
    @RequestMapping(value = "import/template")
    public ApiRest importFileTemplate(HttpServletResponse response) {
        try {
            String fileName = "选课学生导入模板.xlsx";
            List<StudentsExportDTO> templateList = Lists.newArrayList();

            StudentsExportDTO l1 = new StudentsExportDTO();
            l1.setLessonName("正式导入，请删除此说明行.该列的课程必须是系统存在的");
            l1.setTeacher("该课程已存在老师的用户名（或唯一工号）");
            l1.setStudentDept("班级必须是系统存在的");

            StudentsExportDTO l2 = new StudentsExportDTO();
            l2.setLessonName("算法");
            l2.setTeacher("xxl");
            l2.setStudentNum("8002116001");
            l2.setStudentName("学生一");
            l2.setStudentDept("卓越173班");

            StudentsExportDTO l3 = new StudentsExportDTO();
            l3.setStudentNum("8002116002");
            l3.setStudentName("学生二");
            l3.setStudentDept("卓越171班");

            templateList.add(l1);
            templateList.add(l2);
            templateList.add(l3);
            new ExportExcel("选课名单导入模板", StudentsExportDTO.class, 1).setDataList(templateList).write(response, fileName).dispose();
            return super.success();
        } catch (Exception e) {
            return super.failure("导入模板下载失败！失败信息：" + e.getMessage());
        }
    }

    /**
     * 导入Excel
     *
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/import")
    public ApiRest importFile(@RequestParam("file") MultipartFile file) {

        try {
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<StudentsExportDTO> list = ei.getDataList(StudentsExportDTO.class);

            // 导入数据条数
            baseService.importExcel(list);

            // 导入成功
            return super.success();
        } catch (IOException | InstantiationException | IllegalAccessException | InvalidFormatException e) {
            return failure("导入失败，原因：" + e.getMessage());
        }
    }

}
